package com.hzncc.flowable_diboot.config;

import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;

public class TenantIdInterceptor extends TenantLineInnerInterceptor {

    public TenantIdInterceptor(CustomTenantLineHandler customTenantLineHandler) {
        super(customTenantLineHandler);
    }

    @Override
    public Expression buildTableExpression(Table table, Expression where, String whereSegment) {
        return getTenantLineHandler().ignoreTable(table.getName()) ? null : new InExpression(this.getAliasColumn(table), ((CustomTenantLineHandler) getTenantLineHandler()).getTenantIdList(table.getName()));
    }

    @Override
    protected Column getAliasColumn(Table table) {
        StringBuilder column = new StringBuilder();
        if (table.getAlias() != null) {
            column.append(table.getAlias().getName()).append(".");
        } else {
            column.append(table.getName()).append(".");
        }

        column.append(getTenantLineHandler().getTenantIdColumn());
        return new Column(column.toString());
    }
}
